package com.spark.sniffer.logging.schedule;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.spark.sniffer.logging.api.Logger;
import com.spark.sniffer.logging.api.LoggerFactory;
import com.spark.sniffer.logging.config.Config;

/**
 * A sub thread running job to clean the expired log files on scheduled
 * 
 * @author Cobe
 *
 */
public class LogFileCleaner extends Thread {
    private static final Logger log = LoggerFactory.getLogger(LogFileCleaner.class);

    private static final long ONE_DAY_MILLIS = 24 * 3600 * 1000L;

    @Override
    public void run() {
        log.info("Log File Cleaner is running...");
        while (true) {
            if (isOnRunningTime()) {
                cleanExpiredLogFiles();
            }

            sleep4NextRound();
        }

    }

    private boolean isOnRunningTime() {
        // only running on 4 a.m.
        return 4 == Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
    }

    private void sleep4NextRound() {
        try {
            Thread.sleep(1800000L); // 30 minutes per round
        } catch (InterruptedException e) {
        }
    }

    private void cleanExpiredLogFiles() {
        long expiredTime = System.currentTimeMillis() - (Config.Logging.FILE_EXPIRED_DAYS - 1) * ONE_DAY_MILLIS;

        // looking forward 3 days
        SimpleDateFormat sdf = new SimpleDateFormat(Config.Logging.FILE_DATE_FORMAT);

        for (int i = 0; i < 3; i++) {
            expiredTime -= ONE_DAY_MILLIS;

            String logFileName = String.format("%s/%s.%s.log", Config.Logging.DIR, Config.Logging.FILE_NAME,
                sdf.format(new Date(expiredTime)));

            File file = new File(logFileName);
            if (file.exists()) {
                if (file.delete()) {
                    log.info("{} deleted.", logFileName);
                } else {
                    log.warn("Try to delete {} but failed.", logFileName);
                }
            }
        }
    }
}
